﻿using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Threading;
using Framework.Dependency;
using Framework.Security;
using HelperTools;
using Microsoft.Practices.Unity;
using Interfaces.BusinessLogic;
using ServiceInfrastructure.Models.Exceptions;
using ServiceInfrastructure.Models.SecurityModels;
using ServiceInfrastructure.ServiceConstants;

namespace EconomicInformationServiceWcf.ServiceBehaviours
{
    public class EISMessageInspector : IDispatchMessageInspector
    {
        private readonly IInternalSecurityService _securityService;

        public EISMessageInspector()
        {
            _securityService = DependencyManager.Container.Resolve<IInternalSecurityService>();
        }
        
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            var index = request.Headers.FindHeader(ServiceConstants.Headername, ServiceConstants.SecurityServicenamespace);
            if (index != -1)
            {
                var session = request.Headers.GetHeader<EISSession>(index);
                
                var desirializeSession = _securityService.DeserializeTiket(session.With(x => x.Ticket));
                
                if(desirializeSession == null)
                    throw new FaultException<SecurityFault>(new SecurityFault("Invalid ticket"));

                var isSessionValid = _securityService.VerifySession(desirializeSession);
                
                if(!isSessionValid)
                    throw new FaultException<SecurityFault>(new SecurityFault("Session expired"));

                Thread.CurrentPrincipal = new EISSessionPrincipal(desirializeSession);
            }

            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {}
    }
}